import React, { Component } from 'react';

import { 
  Image,
  StyleSheet,
  Alert,
  Button,
  Text,
  View,
  ImageBackground,
  Dimensions,
  ScrollView,
  SafeAreaView,
  TouchableOpacity,
  NativeModules,
  NativeEventEmitter,
  DeviceEventEmitter
} from 'react-native';
import {BoxShadow} from 'react-native-shadow';

const OpenNativeModule = NativeModules.OpenNativeModule;
const SCREEN_WIDTH = Dimensions.get('window').width;
const SCREEN_HEIGHT = Dimensions.get('window').height;
const shadowOpt = {
  width:SCREEN_WIDTH - 20,
  height:170,
  color:'#0450A1',
  border:10,
  radius:5,
  opacity:0.1,
  x:5,
  y:5,
  style:{}
};

const shadowOptCard = {
  width:(SCREEN_WIDTH - 40)/2,
  height:120,
  color:'#0450A1',
  border:6,
  radius:5,
  opacity:0.1,
  x:5,
  y:5,
  style:{}
};

export default class Main extends Component {
  static navigationOptions = {
    header: null
  }
  constructor(props) {
    super(props);
    this.state = {
      date: new Date(),
      mainBtnState: '0',
      mainBtnSrc: require('../assets/mainSwitch_off.png'),
      lampState: '0',
      lampSrc: require('../assets/lamp_off.png'),
      domelightState: '0',
      domelightSrc: require('../assets/domelight_off.png'),
      fanState: '0',
      fanSrc: require('../assets/fan_off.png'),
      btfmState: '00',
      btSrc: require('../assets/bt_off.png'),
      fmSrc: require('../assets/fm_off.png'),
      steamState: '00',
      steamSrc: require('../assets/exhaust_off.png'),
      music: '听见下雨的声音',
      temp: 0,
      runtime: 0,
    };
    // 在ES6中，如果在自定义的函数里使用了this关键字，则需要对其进行“绑定”操作，否则this的指向会变为空
    // 像下面这行代码一样，在constructor中使用bind是其中一种做法（还有一些其他做法，如使用箭头函数等）
    this.mainBt = this.mainBt.bind(this);
    this.lightBt = this.lightBt.bind(this);
    this.lampBt = this.lampBt.bind(this);
    this.fanBt = this.fanBt.bind(this);
    this.broadCastBt = this.broadCastBt.bind(this);
    this.blueToothBt = this.blueToothBt.bind(this);
    this.steamBt = this.steamBt.bind(this);
    this.process = this.process.bind(this);
    this.back = this.back.bind(this);
  }

  componentDidMount() {
    console.log('设备宽高')
    console.log(SCREEN_WIDTH)
    console.log(SCREEN_HEIGHT)
    // 定时器
    this.timerID = setInterval(
      () => this.tick(),
      1000
    );
     //接收原生数据
     this.listener = null;
     if (Platform.OS === 'ios') {
       let eventEmitter = new NativeEventEmitter(OpenNativeModule);
       this.listener = eventEmitter.addListener("CustomEventName", (result) => {
         console.log(result);
         this.process(result)
       })
     } else {
       this.listener = DeviceEventEmitter.addListener("CustomEventName", (result) => {
         console.log(result);
         this.process(result)
       });
     }
    // var data = {
    //   Device_SystemPower: '0',
    //   Device_OneLight: '0',
    //   Device_TwoLight: '0',
    //   Device_SystemFan: '0',
    //   Device_FMBT_StateFreqVol: '0103A202',
    //   Device_SaunaStateTimeTemp: '013C2D',
    //   Device_RoomTemp: 27,
    //   Device_SaunaRunTime: 20,
    //   Device_ErrorImfor: 255,
    //   Device_FMBT_16_Freq: '',
    // }
    // this.process(data)
    // console.log(data);
    // console.log(data.Device_SystemPower)
  }

  componentWillUnmount() {
    clearInterval(this.timerID);
    this.listener && this.listener.remove();
  }

  // 处理实时状态数据
  process(res) {
    // 主开关
    // console.log(res.Device_SystemPower)
    if (res.Device_SystemPower) {
      
      if (this.state.mainBtnState !== res.Device_SystemPower) {
        this.setState({
          mainBtnState: res.Device_SystemPower,
          mainBtnSrc: res.Device_SystemPower=='0'?require('../assets/mainSwitch_off.png'):require('../assets/mainSwitch_on.png')
        });
      }
    }
    // 顶灯
    if (res.Device_OneLight) {
      if (this.state.domelightState !== res.Device_OneLight) {
        this.setState({
          domelightState: res.Device_OneLight,
          domelightSrc: res.Device_OneLight=='0'?require('../assets/domelight_off.png'):require('../assets/domelight_on.png')
        });
      }
    }
    // 幻影灯
    if (res.Device_TwoLight) {
      if (this.state.lampState !== res.Device_TwoLight) {
        this.setState({
          lampState: res.Device_TwoLight,
          lampSrc: res.Device_TwoLight=='0'?require('../assets/lamp_off.png'):require('../assets/lamp_on.png')
        });
      }
    }
    // 风扇
    if (res.Device_SystemFan) {
      if (this.state.fanState !== res.Device_SystemFan) {
        this.setState({
          fanState: res.Device_SystemFan,
          fanSrc: res.Device_SystemFan=='0'?require('../assets/fan_off.png'):require('../assets/fan_on.png')
        });
      }
    }
    // 蓝牙
    if (res.Device_FMBT_StateFreqVol) {
      var state = res.Device_FMBT_StateFreqVol.substr(0, 2)
      if (state !== this.state.btfmState) {
        if (state == '00') {
          // 两个都关
          this.setState({
            btfmState: '00',
            btSrc: require('../assets/bt_off.png'),
            fmSrc: require('../assets/fm_off.png'),
          });
        } else if (state == '01') {
          // 收音机开
          this.setState({
            btfmState: '01',
            btSrc: require('../assets/bt_off.png'),
            fmSrc: require('../assets/fm_on.png'),
          });
        } else {
          // 蓝牙开
          this.setState({
            btfmState: '02',
            btSrc: require('../assets/bt_on.png'),
            fmSrc: require('../assets/fm_off.png'),
          });
        }
      }
    }
    // 蒸汽
    if (res.Device_SaunaStateTimeTemp) {
      var state = res.Device_SaunaStateTimeTemp.substr(0, 2)
      if (this.state.steamState !== state) {
        this.setState({
          steamState: state,
          steamSrc: state=='00'?require('../assets/exhaust_off.png'):require('../assets/exhaust_on.png')
        });
      }
    }
    // 温度
    if (res.Device_RoomTemp) {
      console.log('温度更新')
      if (this.state.temp !== res.Device_RoomTemp) {
        this.setState({
          temp: res.Device_RoomTemp,
        });
      }
    }
    // 运行时间
    if (res.Device_SaunaRunTime) {
      console.log('运行时间更新')
      if (this.state.runtime !== res.Device_SaunaRunTime) {
        this.setState({
          runtime: res.Device_SaunaRunTime,
        });
      }
    }
  }


  // 更新时间
  tick() {
    this.setState({
      date: new Date()
    });
  }

  back() {
   console.log("倒退")
   OpenNativeModule.jumpToNativeView();
  }

  mainBt() {
    console.log('主开关')
    var dataSystemPower
    if (this.state.mainBtnState == '1') {
      this.setState({
        mainBtnSrc: require('../assets/mainSwitch_off.png'),
        mainBtnState: '0'
      });
      dataSystemPower =  {"data":{"deviceName":"Device_SystemPower","value":"0"}};
    } else {
      this.setState({
        mainBtnSrc: require('../assets/mainSwitch_on.png'),
        mainBtnState: '1'
      });
      dataSystemPower =  {"data":{"deviceName":"Device_SystemPower","value":"1"}};
   }
    OpenNativeModule.jump2Native(dataSystemPower).then((result) => {
      console.log(result);
    }).catch((error) => {
      console.log(error);
      Alert.alert(
        '提示',
        '命令发送失败！',
        [
          {text: '确认', onPress: () => console.log('OK Pressed')},
        ]
      )
    });
  }

  lightBt() {
    console.log('顶灯')
    var dataOneLight
    if(this.state.mainBtnState == '0'){
      return;
    }else if (this.state.domelightState == '1') {
      this.setState({
        domelightSrc: require('../assets/domelight_off.png'),
        domelightState: '0'
      });
      dataOneLight = {"data":{"deviceName":"Device_OneLight","value":"0"}};
    } else {
      this.setState({
        domelightSrc: require('../assets/domelight_on.png'),
        domelightState: '1'
      });
      dataOneLight = {"data":{"deviceName":"Device_OneLight","value":"1"}};
    }
    OpenNativeModule.jump2Native(dataOneLight).then((result) => {
      console.log(result);
    }).catch((error) => {
      console.log(error);
      Alert.alert(
        '提示',
        '命令发送失败！',
        [
          {text: '确认', onPress: () => console.log('OK Pressed')},
        ]
      )
    });
  }
  lampBt() {
    console.log('幻影灯')
    var dataTwolight
    if(this.state.mainBtnState == '0'){
      return;
    }else if (this.state.lampState == '1') {
      this.setState({
        lampSrc: require('../assets/lamp_off.png'),
        lampState: '0'
      });
      dataTwolight = {"data":{"deviceName":"Device_TwoLight","value":"0"}};
    } else {
      this.setState({
        lampSrc: require('../assets/lamp_on.png'),
        lampState: '1'
      });
      dataTwolight = {"data":{"deviceName":"Device_TwoLight","value":"1"}};
    }
    OpenNativeModule.jump2Native(dataTwolight).then((result) => {
      console.log(result);
    }).catch((error) => {
      console.log(error);
      Alert.alert(
        '提示',
        '命令发送失败！',
        [
          {text: '确认', onPress: () => console.log('OK Pressed')},
        ]
      )
    });
  }
  fanBt() {
    console.log('排风')
    var dataSystemFan
    if(this.state.mainBtnState == '0'){
      return;
    } else if (this.state.fanState == '1') {
      this.setState({
        fanSrc: require('../assets/fan_off.png'),
        fanState: '0'
      });
      dataSystemFan = {"data":{"deviceName":"Device_SystemFan","value":"0"}};
    } else {
      this.setState({
        fanSrc: require('../assets/fan_on.png'),
        fanState: '1'
      });
      dataSystemFan = {"data":{"deviceName":"Device_SystemFan","value":"1"}};
    }
    OpenNativeModule.jump2Native(dataSystemFan).then((result) => {
      console.log(result);
    }).catch((error) => {
      console.log(error);
      Alert.alert(
        '提示',
        '命令发送失败！',
        [
          {text: '确认', onPress: () => console.log('OK Pressed')},
        ]
      )
    });
  }
  broadCastBt() {
    console.log('广播')
    if(this.state.mainBtnState == '0'){
      return;
    } else {
      this.props.navigation.navigate('PageFM', {title:'FM',btfmState:this.state.btfmState})
    }
  }
  blueToothBt() {
    console.log('蓝牙')
    var dataFMBTState
    if(this.state.mainBtnState == '0'){
      return;
    } else if(this.state.btfmState == '00'|| this.state.btfmState == '01'){
      this.setState({
        btSrc: require('../assets/bt_on.png'),
        btfmState : '02'
      });
      dataFMBTState = {"data":{"deviceName":"Device_FMBT_StateFreqVol","value":"02041501"}}
    } else {
      this.setState({
        btSrc: require('../assets/bt_off.png'),
        btfmState : '00'
      });
      dataFMBTState = {"data":{"deviceName":"Device_FMBT_StateFreqVol","value":"00041501"}}
    }
    
    OpenNativeModule.jump2Native(dataFMBTState).then((result) => {
      console.log(result);
    }).catch((error) => {
      console.log(error);
      Alert.alert(
        '提示',
        '命令发送失败！',
        [
          {text: '确认', onPress: () => console.log('OK Pressed')},
        ]
      )
    })
    // this.props.navigation.navigate('PageBT', {title:'BT'})
  }
  steamBt() {
    console.log('桑拿')
    console.log(this.state.steamState)
    if(this.state.mainBtnState == '0'){
      return;
    } else {
      this.props.navigation.navigate('PageSauna', {title:'Sauna',steamState:this.state.steamState})
    }
  }

  render() {
    return this.renderLoadingView();
  }

  renderLoadingView() {
    return (
      <SafeAreaView style={{ flex: 1 }}>
        <ScrollView contentContainerStyle={{ height: 820 }}>
          {/* <View style={styles.container}> */}
            <ImageBackground source={require('../assets/bg.png')} style={styles.bgImage}>
              <View style={styles.header}>

                <View style={{ width: 30 }}>
                <TouchableOpacity  onPress={this.back}>
                  <Image
                    source={require('../assets/icon_left.png')}
                    style={{ width:11, height:19, marginLeft:14 }}
                  />
                  </TouchableOpacity>
                </View>

                <View style={{ flex: 1, alignItems: 'center' }}>
                  <Text style={{ fontSize: 20, color:'#fff' } }>主设备</Text>
                </View>
                <View style={{ width: 30 }}>
                </View>
              </View>

              <View>
                <TouchableOpacity onPress={this.mainBt}>
                  <Image
                    source={this.state.mainBtnSrc}
                    style={{ width:80, height:80, marginTop:30 }}
                  />
                </TouchableOpacity>
              </View>
              
              <View style={styles.panel_container}>
                <BoxShadow setting={shadowOpt}>
                  <View style={styles.panel}>
                    <View style={styles.panel1}>
                      <Image
                      source={this.state.domelightSrc}
                      style={{ width:22, height:18, marginTop:3 }}/>
                      <Image
                      source={this.state.lampSrc}
                      style={styles.panel1_icon}/>
                      <Image
                      source={this.state.fanSrc}
                      style={styles.panel1_icon}/>
                      <Image
                      source={this.state.steamSrc}
                      style={styles.panel1_icon}/>
                      <Image
                      source={require('../assets/alarm.png')}
                      style={styles.panel1_icon}/>
                    </View>
                    <View style={styles.panel2}>
                      <Text style={styles.fm}>FM</Text>
                      <Text style={{ fontSize: 12, }}> ···· {this.state.music} ···· </Text>
                      <Text style={styles.fm}>MHZ</Text>
                    </View>
                    <View style={styles.panel3}>
                      <Text style={{ fontSize: 44 }}>{this.state.date.getHours()} : {this.state.date.getMinutes()}</Text>
                    </View>
                    <View style={styles.panel4}>
                      <Image
                        source={this.state.btSrc}
                        style={{ width: 12, height:17 }}/>
                      <Image
                        source={this.state.fmSrc}
                        style={{ width: 22, height:18 }}/>
                      <View style={{ flexDirection: 'row' }}>
                        <Image
                          source={require('../assets/timer.png')}
                          style={{ width: 22, height:22 }}/>
                        <Text style={styles.temp}>{this.state.runtime}分钟</Text>
                      </View>
                      <View style={{ flexDirection: 'row' }}>
                        <Image
                          source={require('../assets/temp.png')}
                          style={{ width: 12, height:24 }}/>
                        <Text style={styles.temp}>{this.state.temp}℃</Text>
                      </View>
                    </View>
                  </View>
                </BoxShadow>
              </View>
              <View style={styles.container_card}>
                <View style={{ flexDirection: 'row', justifyContent: 'space-between' }}>
                  <BoxShadow setting={shadowOptCard}>
                    <ImageBackground source={require('../assets/bgImg.png')} style={styles.card}>
                    <TouchableOpacity style={styles.touch} onPress={this.lightBt}>
                      <Image
                        source={require('../assets/domelight.png')}
                        style={{ width: 55, height:45 }}/>
                      <Text style={styles.card_text}>顶灯</Text>
                    </TouchableOpacity>
                    </ImageBackground>
                  </BoxShadow>
                  <BoxShadow setting={shadowOptCard}>
                    <ImageBackground source={require('../assets/bgImg.png')} style={styles.card}>
                    <TouchableOpacity style={styles.touch} onPress={this.lampBt}>
                      <Image
                        source={require('../assets/lamp.png')}
                        style={{ width: 60, height:60 }}/>
                      <Text style={styles.card_text}>幻影灯</Text>
                    </TouchableOpacity>
                    </ImageBackground>
                  </BoxShadow>
                </View>
                <View style={{ flexDirection: 'row', justifyContent: 'space-between', marginTop:10 }}>
                  <BoxShadow setting={shadowOptCard}>
                    <ImageBackground source={require('../assets/bgImg.png')} style={styles.card}>
                    <TouchableOpacity style={styles.touch} onPress={this.fanBt}>
                      <Image
                        source={require('../assets/icon_fan.png')}
                        style={{ width: 52, height:52 }}/>
                      <Text style={styles.card_text}>排风</Text>
                    </TouchableOpacity>
                    </ImageBackground>
                  </BoxShadow>
                  <BoxShadow setting={shadowOptCard}>
                    <ImageBackground source={require('../assets/bgImg.png')} style={styles.card}>
                    <TouchableOpacity style={styles.touch} onPress={this.broadCastBt}>
                      <Image
                        source={require('../assets/broadcast.png')}
                        style={{ width: 56, height:45 }}/>
                      <Text style={styles.card_text}>广播</Text>
                    </TouchableOpacity>
                    </ImageBackground>
                  </BoxShadow>
                </View>
                <View style={{ flexDirection: 'row', justifyContent: 'space-between', marginTop:10 }}>
                  <BoxShadow setting={shadowOptCard}>
                    <ImageBackground source={require('../assets/bgImg.png')} style={styles.card}>
                    <TouchableOpacity style={styles.touch} onPress={this.blueToothBt}>
                      <Image
                        source={require('../assets/bluetooth.png')}
                        style={{ width: 52, height:52 }}/>
                      <Text style={styles.card_text}>蓝牙</Text>
                    </TouchableOpacity>
                    </ImageBackground>
                  </BoxShadow>
                  <BoxShadow setting={shadowOptCard}>
                    <ImageBackground source={require('../assets/bgImg.png')} style={styles.card}>
                    <TouchableOpacity style={styles.touch} onPress={this.steamBt}>
                      <Image
                        source={require('../assets/steam.png')}
                        style={{ width: 56, height:50 }}/>
                      <Text style={styles.card_text}>桑拿</Text>
                    </TouchableOpacity>
                    </ImageBackground>
                  </BoxShadow>
                </View>
              </View>
            </ImageBackground>
        </ScrollView>
      </SafeAreaView>
    );
  }
}

var styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    // flexDirection: 'row',
    // justifyContent: 'flex-start',
    // alignItems: 'flex-start',
    // backgroundColor: '#F5FCFF'
  },
  bgImage: {
    flex: 1,
    width: SCREEN_WIDTH,
    height: 330,
    // justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F6F6F6',
  },
  header: {
    flexDirection: 'row',
    width: SCREEN_WIDTH,
    marginTop:33,
    justifyContent: 'center',
  },
  panel_container: {
    marginTop: 30,
  },
  panel: {
    height: 170,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: '#fff',
    borderRadius: 5,
  },
  panel1: {
    flex: 2,
    paddingTop: 10,
    flexDirection: 'row',
    justifyContent: 'space-around',
    width: SCREEN_WIDTH - 40,
    borderBottomColor: '#C0C4CC',
    borderBottomWidth: 0.7,
  },
  panel1_icon: {
    width: 22,
    height: 22,
  },
  panel2: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'center',
    width: SCREEN_WIDTH - 40,
    padding: 10
  },
  fm: {
    fontSize: 12,
    borderColor:'#093774',
    borderRadius:3,
    borderWidth: 1,
    width:36,
    alignItems: 'center',
    textAlign: 'center',
  },
  panel3: {
    flex: 3,
    width: SCREEN_WIDTH - 40,
    alignItems: 'center',
    justifyContent: 'center',
    borderBottomColor: '#C0C4CC',
    borderBottomWidth: 0.5,
  },
  panel4: {
    flex: 2,
    width: SCREEN_WIDTH - 40,
    paddingTop: 10,
    flexDirection: 'row',
    justifyContent: 'space-around',
  },
  temp: {
    marginLeft: 5
  },
  container_card: {
    marginTop: 20,
    width: SCREEN_WIDTH - 20,
  },
  card: {
    width: (SCREEN_WIDTH - 40)/2,
    height: 120,
    borderRadius: 10,
    alignItems: 'center',
    justifyContent: 'center',
  },
  touch: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  card_text: {
    fontSize: 22,
    marginLeft: 20
  }
});